package com.ruoyi.web.controller.qx;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.QxChestnutAdoptModel;
import com.ruoyi.system.service.IQxChestnutAdoptModelService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.QxChestnutAdoptModel;
import com.ruoyi.system.service.IQxChestnutAdoptModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 板栗树认领主Controller
 * 
 * @author ruoyi
 * @date 2023-07-28
 */
@RestController
@RequestMapping("/system/model")
public class QxChestnutAdoptModelController extends BaseController
{
	

	@SuppressWarnings("rawtypes")
	@Autowired
	private RedisTemplate redisTemplate;// redis相关操作类

    @Autowired
    private IQxChestnutAdoptModelService qxChestnutAdoptModelService;

    /**
     * 查询板栗树认领主列表
     */
//    @PreAuthorize("@ss.hasPermi('system:model:list')")
    @GetMapping("/list")
    public TableDataInfo list(QxChestnutAdoptModel qxChestnutAdoptModel)
    {
        startPage();
        List<QxChestnutAdoptModel> list = qxChestnutAdoptModelService.selectQxChestnutAdoptModelList(qxChestnutAdoptModel);
        return getDataTable(list);
    }

    /**
     * 导出板栗树认领主列表
     */
    @PreAuthorize("@ss.hasPermi('system:model:export')")
    @Log(title = "板栗树认领主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QxChestnutAdoptModel qxChestnutAdoptModel)
    {
        startPage();
        this.qxChestnutAdoptModelService.exportModelListToExcelService(response,qxChestnutAdoptModel);
    }






    @Log(title = "导入", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        String operName = getUsername();
        String message =  qxChestnutAdoptModelService.importDataTreeChestnut(file,updateSupport,operName);
        return success(message);
    }


    /**
     * 树木图片上传
     */
//    @Log(title = "树木图片上传", businessType = BusinessType.UPDATE)
    @PostMapping("/blUpload")
    public AjaxResult avatar(@RequestParam("file") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
           return qxChestnutAdoptModelService.blUploadImage(file);
        }
        return error("上传图片异常，请联系管理员");
    }


    /**
     * 下载模板
     * @param response
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        qxChestnutAdoptModelService.importTemplateThreeExcel(response);
    }

    /**
     * 获取板栗树认领主详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:model:query')")
    @GetMapping(value = "/{treeId}")
    public AjaxResult getInfo(@PathVariable("treeId") Long treeId)
    {
        return success(qxChestnutAdoptModelService.selectQxChestnutAdoptModelByTreeId(treeId));
    }

    /**
     * 新增板栗树认领主
     */
    @PreAuthorize("@ss.hasPermi('system:model:add')")
    @Log(title = "板栗树认领主", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody QxChestnutAdoptModel qxChestnutAdoptModel)
    {
        return toAjax(qxChestnutAdoptModelService.insertQxChestnutAdoptModel(qxChestnutAdoptModel));
    }

    /**
     * 修改板栗树认领主
     */
    @PreAuthorize("@ss.hasPermi('system:model:edit')")
    @Log(title = "板栗树认领主", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QxChestnutAdoptModel qxChestnutAdoptModel)
    {
        return toAjax(qxChestnutAdoptModelService.updateQxChestnutAdoptModel(qxChestnutAdoptModel));
    }

    /**
     * 删除板栗树认领主
     */
    @PreAuthorize("@ss.hasPermi('system:model:remove')")
    @Log(title = "板栗树认领主", businessType = BusinessType.DELETE)
	@DeleteMapping("/{treeIds}")
    public AjaxResult remove(@PathVariable Long[] treeIds)
    {
        return toAjax(qxChestnutAdoptModelService.deleteQxChestnutAdoptModelByTreeIds(treeIds));
    }

    /**
     * 树苗认养申请接口
     * @param qxChestnutAdoptModel
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
	@PostMapping("/apply")
    public AjaxResult apply(@RequestBody QxChestnutAdoptModel qxChestnutAdoptModel) throws Exception{
    	if (qxChestnutAdoptModel == null) {
			return error("申请信息为空，不能继续！");
		}
		if (qxChestnutAdoptModel.getTreeId() == null) {
			return error("要认养的树苗为空，不能继续！");
		}
		if (StringUtils.isBlank(qxChestnutAdoptModel.getPersonPhone())) {
			return error("请填写认养人联系方式！");
		}
		if (StringUtils.isBlank(qxChestnutAdoptModel.getAdoptivePerson())) {
			return error("请填写认养人信息！");
		}
		//判断重复提交
		//判断是否缓存中有数据，如果没有，则写入缓存，事务完成后清理缓存，如果存在，则提示有申请中的数据
		ValueOperations<String, String> objOps = redisTemplate.opsForValue();
		String applyTreeId = objOps.get("applyId"+qxChestnutAdoptModel.getTreeId());
		if (applyTreeId == null || "".equals(applyTreeId)) {
			objOps.set("applyId"+qxChestnutAdoptModel.getTreeId(), qxChestnutAdoptModel.getAdoptivePerson());
		} else {
			return error("存在树苗申请中的记录，不能重复提交");
		}
    	try {
    		qxChestnutAdoptModelService.apply(qxChestnutAdoptModel);
		} catch (Exception e) {
			//出现异常清理key，让下一次请求进来
			redisTemplate.delete("applyId"+qxChestnutAdoptModel.getTreeId());
			return error(e.getMessage());
		}
    	//业务完成清理key，同一个树苗如果已经被领养，则apply方法中会进行逻辑判断
    	redisTemplate.delete("applyId"+qxChestnutAdoptModel.getTreeId());
    	return success("认养申请成功");
	}


    /**
     *申请审核接口
     */
    @PreAuthorize("@ss.hasPermi('system:model:approve')")
    @Log(title = "认养申请审核", businessType = BusinessType.UPDATE)
	@PostMapping("/approve")
    public AjaxResult approve(@RequestBody String param)
    {
		JSONObject obj = JSONObject.parseObject(param);
    	return qxChestnutAdoptModelService.approve(obj);//success("审核成功");
    }
}
